package cn.hpclub.server.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.util.InterfaceUtil;

public class Reward extends Model<Reward>{
    private static final Logger logger        = LoggerFactory.getLogger(Reward.class);
    public static final Reward  dao           = new Reward();

    public static String        ID            = "id";                                 // 酬金id
    public static String        APPID         = "appid";                              // 酬金机构
    public static String        ORG_ID        = "org_id";                             // 酬金机构
    public static String        BUSINESS_ID   = "business_id";                        // 酬金业务
    public static String        FIRST_REWARD  = "first_remuneration";                 // 首单酬金
    public static String        NORMAL_REWARD = "normal_remuneration";                // 正常酬金
    public static String        SINGLE_CAP    = "single_cap";                         // 修改时间
    public static String        MODIFY_DATE   = "modifyDate";
    public static String        ENABLED       = "enabled";
    public static String        CHANNELID     = "channel_typeid";
    public static String        REWARDID      = "rewardid";
    public static String        DELETE        = "is_deleted";

    public Page<Record> list(int number, int size, int orgId, String busName, String busCode){
        try{
            List<Object> p = new ArrayList<Object>();
            StringBuffer sql_select = new StringBuffer();
            StringBuffer sql_from = new StringBuffer();
            sql_select.append("select " + Constant.Table.REWARD + ".*," + Constant.Table.BUSIENSS + "."
                    + Business.BUSINESS_CODE + "," + Constant.Table.BUSIENSS + "." + Business.BUSINESS_NAME + ","
                    + Constant.Table.ORGANIZATION + "." + Organization.DISPLAYNAME);

            sql_from.append(" from " + Constant.Table.REWARD + "," + Constant.Table.BUSIENSS + ","
                    + Constant.Table.ORGANIZATION);
            sql_from.append(" where " + Constant.Table.ORGANIZATION + "." + Organization.ID + "="
                    + Constant.Table.REWARD + "." + Reward.ORG_ID);

            sql_from.append(" and " + Constant.Table.REWARD + "." + Reward.BUSINESS_ID + "=" + Constant.Table.BUSIENSS
                    + "." + Business.ID);
            sql_from.append(" and " + Constant.Table.REWARD + "." + Reward.BUSINESS_ID + " in (select " + Business.ID
                    + " from " + Constant.Table.BUSIENSS + " where " + Business.BUSINESS_CODE + " like ? and "
                    + Business.BUSINESS_NAME + " like ?)");
            p.add("%" + busCode + "%");
            p.add("%" + busName + "%");
            if(orgId != InterfaceUtil.getIdTop() && orgId > 0){
                sql_from.append(" and " + Constant.Table.REWARD + "." + Reward.ORG_ID + "=?");
                p.add(orgId);
            }
            sql_from.append(" and " + Constant.Table.ORGANIZATION + "." + Organization.ID + " in "
                    + InterfaceUtil.getChlidOrgIdSql(InterfaceUtil.getOrgId(), 1, true));

            return Db.paginate(number, size, sql_select.toString(), sql_from.toString(), p.toArray());
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public List<Record> getOrg(){
        try{
            int id = InterfaceUtil.getOrgId();
            StringBuffer sql = new StringBuffer("select " + Organization.ID + "," + Organization.DISPLAYNAME + " from "
                    + Constant.Table.ORGANIZATION + " where ");
            if(id == InterfaceUtil.getIdTop()){
                sql.append(Organization.PARENTID + "=?");
            } else{
                sql.append(Organization.ID + "=?");
            }

            List<Record> list = Db.find(sql.toString(), new Object[] { id });
            if(list == null){
                list = new ArrayList<Record>();
            }
            if(id == InterfaceUtil.getIdTop()){
                Record r = new Record();
                r.set(Organization.ID, InterfaceUtil.getIdTop());
                r.set(Organization.DISPLAYNAME, "全部");
                list.add(0, r);
            }
            return list;

        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public Reward preview(int id){
        try{
            return new Reward().findById(id);

        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public List<Record> getChannel(int id){
        try{
            return Db.find("select " + Constant.Table.REWARD_CHANNEL + "." + CHANNELID + ","
                    + Constant.Table.ORGANIZATION_CLASS + "." + Website.WEBSITE_ID + " from "
                    + Constant.Table.REWARD_CHANNEL + "," + Constant.Table.ORGANIZATION_CLASS + " where " + REWARDID
                    + "=? and " + Constant.Table.REWARD_CHANNEL + "." + CHANNELID + "="
                    + Constant.Table.ORGANIZATION_CLASS + "." + Website.ID, new Object[] { id });
        }
        catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public boolean checkUnique(int id, int org, int busi){
        try{

            List<Record> result = Db.find(
                                          "select " + Reward.ID + " from " + Constant.Table.REWARD + " where "
                                                  + Reward.ORG_ID + "=? and " + Reward.BUSINESS_ID + "=?",
                                          new Object[] { org, busi });

            if(result.size() <= 0 || result.get(0).getInt("id") == id){

                return true;
            }

            return false;

        }
        catch(Exception e){
            e.printStackTrace();

            return true;
        }
    }

    @Before({ Tx.class })
    public boolean delete(String[] ids){
        try{

            StringBuffer in = new StringBuffer();
            in.append("(");
            for(int i = 0; i < ids.length; i++){
                in.append("?,");
            }
            if(in.length() >= 1){
                in = new StringBuffer(in.substring(0, in.length() - 1) + ")");
            }

            return Db.update("delete from " + Constant.Table.REWARD + " where " + Reward.ID + " in " + in,
                             ids) == ids.length;

        }
        catch(Exception e){
            return false;
        }
    }

    public void update(Map<String, String[]> map, String[] channel){

        Reward r = new Reward().findById(map.get(Reward.ID)[0]);
        r.set(Reward.ORG_ID, map.get(Reward.ORG_ID)[0]);
        r.set(Reward.BUSINESS_ID, map.get(Reward.BUSINESS_ID)[0]);
        r.set(Reward.FIRST_REWARD, map.get(Reward.FIRST_REWARD)[0]);
        r.set(Reward.NORMAL_REWARD, map.get(Reward.NORMAL_REWARD)[0]);
        r.set(Reward.SINGLE_CAP, StrKit.notBlank(map.get(Reward.SINGLE_CAP)[0]) ? map.get(Reward.SINGLE_CAP)[0] : 0);
        r.set(Reward.ENABLED, Boolean.parseBoolean(map.get(Reward.ENABLED)[0]));

        if(r.update()){
            int rewardid = r.getInt("id");
            StringBuffer sql = new StringBuffer();
            StringBuffer sql_delete = new StringBuffer();
            List<Object> p_delete = new ArrayList<Object>();
            p_delete.add(rewardid);
            for(int i = 0; i < channel.length; i++){
                sql.append(",(?," + rewardid + ")");
                sql_delete.append(",?");
                p_delete.add(channel[i]);
            }
            if(sql.length() > 0){
                sql = new StringBuffer(sql.substring(1));
            }
            if(sql_delete.length() > 0){
                sql_delete = new StringBuffer("(" + sql_delete.substring(1) + ")");
            }
            Db.update("delete from " + Constant.Table.REWARD_CHANNEL + " where " + REWARDID + "=? and " + CHANNELID
                    + " not in " + sql_delete, p_delete.toArray());
            Db.update("insert into " + Constant.Table.REWARD_CHANNEL + " (" + CHANNELID + "," + REWARDID + ") values "
                    + sql + " on duplicate key update " + CHANNELID + "=" + CHANNELID, channel);
        }

    }

    public void insert(Map<String, String[]> map, String[] channel){
        try{
            Reward r = new Reward();
            Iterator<String> iterator = map.keySet().iterator();
            String pattr = null;
            r.set(Reward.ORG_ID, map.get(Reward.ORG_ID)[0]);
            r.set(Reward.BUSINESS_ID, map.get(Reward.BUSINESS_ID)[0]);
            r.set(Reward.FIRST_REWARD, map.get(Reward.FIRST_REWARD)[0]);
            r.set(Reward.NORMAL_REWARD, map.get(Reward.NORMAL_REWARD)[0]);
            r.set(Reward.SINGLE_CAP,
                  StrKit.notBlank(map.get(Reward.SINGLE_CAP)[0]) ? map.get(Reward.SINGLE_CAP)[0] : 0);
            r.set(Reward.ENABLED, Boolean.parseBoolean(map.get(Reward.ENABLED)[0]));

            if(r.save()){
                int rewardid = r.getInt("id");
                StringBuffer sql = new StringBuffer();
                Object[] p = new Object[] {};
                for(int i = 0; i < channel.length; i++){
                    sql.append(",(?," + rewardid + ")");

                }
                if(sql.length() > 0){
                    sql = new StringBuffer(sql.substring(1));
                }
                Db.update("insert into " + Constant.Table.REWARD_CHANNEL + " (" + CHANNELID + "," + REWARDID
                        + ") values " + sql + " on duplicate key update " + CHANNELID + "=" + CHANNELID, channel);
            }

        }
        catch(Exception e){
            e.printStackTrace();

        }
    }

}
